

function createRoute(record, location) { // 创建路由
    let matched = []
    if (record) {
        while (record) {
            matched.unshift(record) // [about, aboutA] 父组件在前
            record = record.parent
        }
    }

    return {
        ...location,
        matched
    }
}

function runQueue(queue, form, to, cb) {

    function next(index) {
        if (index >= queue.length) {
            return cb()
        }
        let hook = queue[index]
        hook(form, to, () => next(index + 1))
    }

    next(0)
}

class Base {
    constructor(router) {
        this.router = router
        this.current = createRoute(null, {
            path: '/'
        })
    }

    transitionTo(location, listener) {

        let record = this.router.match(location)
        let route = createRoute(record, { path: location })
        if (location === this.current.path
            && this.current.matched.length === route.matched.length) {
            return
        }
        let queue = [].concat(this.router.beforeEachHooks) // 导航狗子维护为队列
        console.log(queue)
        runQueue(queue, this.current, route, () => { //  钩子执行完成后， 在渲染页面
            this.current = route
            // path:'/about/a',matched[aboutRecord, aboutARecord]
            //  每次更新的是 current  当current变化时 需要重新调用transitionTo 再次拿到新的记录
            listener && listener()
            this.cb && this.cb(route)
        })


    }
    listen(cb) {
        this.cb = cb
    }
}


export default Base